//
//  PhotoView.m
//  OrderSeat
//
//  Created by 王威 on 13-12-11.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "PhotoView.h"
#import "TMPhotoQuiltViewCell.h"
#import "UIImageView+WebCache.h"
#import "PhotoViewController.h"
#import "PhotoDetailViewController.h"

@implementation PhotoView

- (id)initWithFrame:(CGRect)frame shopId:(NSString*)shopId type:(int)type
{
    self = [super initWithFrame:frame];
    if (self) {
        self.type = type;
        self.shopId = shopId;
        _dataSource = [[PhotoViewDataSource alloc] initWithView:self];
        [self initViews];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame userName:(NSString *)userName type:(int)type
{
    self = [super initWithFrame:frame];
    if (self) {
        self.type = type;
        self.userName = userName;
        _dataSource = [[PhotoViewDataSource alloc] initWithView:self];
        [self initViews];
    }
    return self;
}

- (void)initViews
{
    _qtmquitView = [[TMQuiltView alloc] initWithFrame:self.bounds];
	_qtmquitView.delegate = self;
	_qtmquitView.dataSource = self;
    
	[self addSubview:_qtmquitView];
    
    [self createHeaderView];
    
    [self autoPullRefresh];
}

- (void)autoPullRefresh
{
    [_qtmquitView setContentOffset:CGPointMake(0, -75) animated:YES];
    [self performSelector:@selector(doPullRefresh) withObject:nil];
}

//执行下拉刷新
-(void)doPullRefresh {
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self.qtmquitView];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.qtmquitView];
}

-(void)createHeaderView{
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:
                          CGRectMake(Zero, Zero - ScreenHeight, ScreenWidth, ScreenHeight)];
    _refreshHeaderView.delegate = self;
    
	[_qtmquitView addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void)setFooterView
{
    CGFloat height = MAX(_qtmquitView.contentHeight, _qtmquitView.height);
    if (_refreshFooterView && [_refreshFooterView superview])
	{
        _refreshFooterView.frame = CGRectMake(0.0f, height, _qtmquitView.width, ScreenHeight);
    }
    else
	{
        _refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:
                              CGRectMake(0.0f, height,
                                         _qtmquitView.width, ScreenHeight)];
        _refreshFooterView.delegate = self;
        [_qtmquitView addSubview:_refreshFooterView];
    }
    
    if (_refreshFooterView)
	{
        [_refreshFooterView refreshLastUpdatedDate];
    }
}

-(void)removeFooterView
{
    if (_refreshFooterView && [_refreshFooterView superview])
	{
        [_refreshFooterView removeFromSuperview];
    }
    _refreshFooterView = nil;
}

//===============
//刷新delegate
#pragma mark -
#pragma mark data reloading methods that must be overide by the subclass
-(void)beginToReloadData:(EGORefreshPos)aRefreshPos
{
	_reloading = YES;
    
    if (aRefreshPos == EGORefreshHeader)
	{
        [self performSelector:@selector(refreshView) withObject:nil afterDelay:2.0];
    }
    else if(aRefreshPos == EGORefreshFooter)
	{
        [self performSelector:@selector(getNextPageView) withObject:nil afterDelay:2.0];
    }
}

//刷新调用的方法
-(void)refreshView
{
    _dataSource.pageNumber = 1;
    [_dataSource fetchPhotoWithPage:_dataSource.pageNumber];
}
//加载调用的方法
-(void)getNextPageView
{
    [_dataSource fetchPhotoWithPage:_dataSource.pageNumber+1];
    
    [self removeFooterView];
}

-(void)finishedLoadData
{
    [_qtmquitView reloadData];
    [self finishReloadingData];
    [self setFooterView];
}

- (void)finishReloadingData
{
	_reloading = NO;
    
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_qtmquitView];
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:_qtmquitView];
        [self setFooterView];
    }
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (_refreshHeaderView)
	{
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
	
	if (_refreshFooterView)
	{
        [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (_refreshHeaderView)
	{
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
	
	if (_refreshFooterView)
	{
        [_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}

#pragma mark -
#pragma mark EGORefreshTableDelegate Methods
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos
{
	[self beginToReloadData:aRefreshPos];
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view
{
	return _reloading; // should return if data source model is reloading
}

// if we don't realize this method, it won't display the refresh timestamp
- (NSDate*)egoRefreshTableDataSourceLastUpdated:(UIView*)view
{
	return [NSDate date]; // should return date data source was last changed
}

- (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView
{
    return _dataSource.photoList.count;
}

- (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath
{
    TMPhotoQuiltViewCell *cell = (TMPhotoQuiltViewCell *)[quiltView dequeueReusableCellWithReuseIdentifier:@"PhotoCell"];
    if (!cell) {
        cell = [[TMPhotoQuiltViewCell alloc] initWithReuseIdentifier:@"PhotoCell"];
    }
    
    NSDictionary *dic = [_dataSource.photoList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    cell.isUserCenter = _isUserCenter;
    cell.delegate = self;
    
    return cell;
}

- (void)deleteDidSelect:(NSDictionary *)dic
{
    self.selectRow = dic;
    NSString *pid = [dic objectForKey:@"id"];
    [_dataSource deletePhotoWithId:pid];
}

#pragma mark - TMQuiltViewDelegate

- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_dataSource.photoList objectAtIndex:indexPath.row];
    
    NSLog(@"dic:%@",dic);
    
    float height = [[dic objectForKey:@"pheight"] floatValue];
    float width = [[dic objectForKey:@"pwidth"] floatValue];
    width = width <= 0 ? 1 : width;
    height = height <= 0 ? 1 : height;
    
    return height / (width/150) + 20;
}

- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_dataSource.photoList objectAtIndex:indexPath.row];
    NSString *photoId = [dic objectForKey:@"id"];
    PhotoDetailViewController *detailVC = [[PhotoDetailViewController alloc] initWithId:photoId];
    [self.photoVC.navigationController pushViewController:detailVC animated:YES];
}

- (void)removeFinished
{
    [_dataSource.photoList removeObject:_selectRow];
    [_qtmquitView reloadData];
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation PhotoViewDataSource

#define RefreshTag 1001
#define LoadMoreTag 1002
#define DEL_PHOTO_TAG 1003
#define kAPI_ENV 1
#define kAPI_DISH 2

- (id)initWithView:(id)view
{
    self = [super init];
    if (self) {
        self.view = view;
        _photoList = [[NSMutableArray alloc] initWithCapacity:5];
        _pageNumber = 1;
    }
    return self;
}

- (void)deletePhotoWithId:(NSString *)pid
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_DEL_PHOTO, pid];
    [self get:url tag:DEL_PHOTO_TAG];
}

- (void)fetchPhotoWithPage:(int)page
{
    NSString *url = [self getURL:_view.type page:page];
    [self get:url tag:page == 1 ? RefreshTag : LoadMoreTag];
}

- (NSString *)getURL:(int)type page:(int)page
{
    if (type == kAPI_ENV) {
        if (_view.shopId) {
            return [NSString stringWithFormat:API_SHOP_PHOTO_ENV,_view.shopId,page];
        }
        else if(_view.userName) {
            return [NSString stringWithFormat:API_MY_PHOTO_ENV,_view.userName,page];
        }
        return [NSString stringWithFormat:API_PHOTO_ENV,page,[AppSetting cityId]];
    }
    else if (type == kAPI_DISH) {
        if (_view.shopId) {
            return [NSString stringWithFormat:API_SHOP_PHOTO_DISH,_view.shopId,page];
        }
        else if(_view.userName) {
            return [NSString stringWithFormat:API_MY_PHOTO_DISH,_view.userName,page];
        }
        return [NSString stringWithFormat:API_PHOTO_DISH,page,[AppSetting cityId]];
    }
    else {
        if (_view.shopId) {
            return [NSString stringWithFormat:API_SHOP_PHOTO_ALL,_view.shopId,page];
        }
        else if(_view.userName) {
            return [NSString stringWithFormat:API_MY_PHOTO_ALL,_view.userName,page];
        }
        return [NSString stringWithFormat:API_PHOTO_ALL,page,[AppSetting cityId]];
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"data:%@",request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    if (request.tag == RefreshTag) {
        self.photoList = [data objectForKey:@"photo"];
        [_view finishedLoadData];
    }
    
    if (request.tag == LoadMoreTag) {
        _pageNumber++;
        [_photoList addObjectsFromArray:[data objectForKey:@"photo"]];
        [_view finishedLoadData];
    }
    
    if (request.tag == DEL_PHOTO_TAG) {
        [SVProgressHUD dismiss];
        
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            [_view removeFinished];
        }
        
        if (state == 2) {
            [AppDelegate showMessage:@"图片删除失败"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [_view finishedLoadData];
    [super requestFailed:request];
}

@end
